package com.cdp.web.controller.system;

import java.time.ZoneId;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cdp.system.domain.SysUserAttribute;
import com.cdp.system.dto.UserDTO;
import com.cdp.system.service.*;
import com.cdp.system.vo.SysUserVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.cdp.common.annotation.Log;
import com.cdp.common.core.controller.BaseController;
import com.cdp.common.core.domain.AjaxResult;
import com.cdp.common.core.domain.entity.SysDept;
import com.cdp.common.core.domain.entity.SysRole;
import com.cdp.common.core.domain.entity.SysUser;
import com.cdp.common.core.page.TableDataInfo;
import com.cdp.common.enums.BusinessType;
import com.cdp.common.utils.SecurityUtils;
import com.cdp.common.utils.StringUtils;
import com.cdp.common.utils.poi.ExcelUtil;



/**
 * 用户信息
 *
 * @author ruoyi
 */
@RestController
@RequestMapping("/system/user")
@Slf4j
public class SysUserController extends BaseController {
    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private ISysPostService postService;

    @Autowired
    private ISysRoleService sysRoleService;

    private static final String PHONE_NUMBER = "^1[3-9]\\d{9}$";

    /**
     * 获取用户列表
     */
    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysUser user) {
        startPage();
        List<SysUser> list = userService.selectUserList(user);
        return getDataTable(list);
    }

    @Log(title = "用户管理", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('system:user:export')")
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysUser user) {
        List<SysUser> list = userService.selectUserList(user);
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        util.exportExcel(response, list, "用户数据");
    }

    @Log(title = "用户管理", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('system:user:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        List<SysUser> userList = util.importExcel(file.getInputStream());
        String operName = getUsername();
        String message = userService.importUser(userList, updateSupport, operName);
        return success(message);
    }

    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        util.importTemplateExcel(response, "用户数据");
    }

    /**
     * 根据用户编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:user:query')")
    @GetMapping(value = {"/", "/{userId}"})
    public AjaxResult getInfo(@PathVariable(value = "userId", required = false) Long userId) {
        userService.checkUserDataScope(userId);
        AjaxResult ajax = AjaxResult.success();
        List<SysRole> roles = roleService.selectRoleAll();
        ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        ajax.put("posts", postService.selectPostAll());
        if (StringUtils.isNotNull(userId)) {
            SysUser sysUser = userService.selectUserById(userId);
            ajax.put(AjaxResult.DATA_TAG, sysUser);
            ajax.put("postIds", postService.selectPostListByUserId(userId));
            ajax.put("roleIds", sysUser.getRoles().stream().map(SysRole::getRoleId).collect(Collectors.toList()));
        }
        return ajax;
    }

    /**
     * 新增用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:add')")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysUser user) {
        deptService.checkDeptDataScope(user.getDeptId());
        roleService.checkRoleDataScope(user.getRoleIds());
        if (!userService.checkUserNameUnique(user)) {
            return error("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user)) {
            return error("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user)) {
            return error("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setCreateBy(getUsername());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        return toAjax(userService.save(user));
    }

    /**
     * 修改用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        deptService.checkDeptDataScope(user.getDeptId());
        roleService.checkRoleDataScope(user.getRoleIds());
        if (!userService.checkUserNameUnique(user)) {
            return error("修改用户'" + user.getUserName() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user)) {
            return error("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user)) {
            return error("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setUpdateBy(getUsername());
        return toAjax(userService.updateUser(user));
    }

    /**
     * 删除用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:remove')")
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{userIds}")
    public AjaxResult remove(@PathVariable Long[] userIds) {
        if (ArrayUtils.contains(userIds, getUserId())) {
            return error("当前用户不能删除");
        }
        return toAjax(userService.deleteUserByIds(userIds));
    }

    /**
     * 重置密码
     */
    @PreAuthorize("@ss.hasPermi('system:user:resetPwd')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/resetPwd")
    public AjaxResult resetPwd(@RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        user.setUpdateBy(getUsername());
        return toAjax(userService.resetPwd(user));
    }

    /**
     * 状态修改
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        user.setUpdateBy(getUsername());
        return toAjax(userService.updateUserStatus(user));
    }

    /**
     * 根据用户编号获取授权角色
     */
    @PreAuthorize("@ss.hasPermi('system:user:query')")
    @GetMapping("/authRole/{userId}")
    public AjaxResult authRole(@PathVariable("userId") Long userId) {
        AjaxResult ajax = AjaxResult.success();
        SysUser user = userService.selectUserById(userId);
        List<SysRole> roles = roleService.selectRolesByUserId(userId);
        ajax.put("user", user);
        ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        return ajax;
    }

    /**
     * 用户授权角色
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.GRANT)
    @PutMapping("/authRole")
    public AjaxResult insertAuthRole(Long userId, Long[] roleIds) {
        userService.checkUserDataScope(userId);
        roleService.checkRoleDataScope(roleIds);
        userService.insertUserAuth(userId, roleIds);
        return success();
    }

    /**
     * 获取部门树列表
     */
    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @GetMapping("/deptTree")
    public AjaxResult deptTree(SysDept dept) {
        return success(deptService.selectDeptTreeList(dept));
    }


    /**
     * 查询用户列表
     */
//    @GetMapping("listUser")
//    public AjaxResult listUser() {
//
//        List<SysUser> userLists = userService.list();
//        ArrayList<SysUserVO> sysUserVOS = new ArrayList<>();
//        for (SysUser userList : userLists) {
//            SysUserVO sysUserVO = new SysUserVO();
//            sysUserVO.setUserName(userList.getUserName());
//            sysUserVO.setPhonenumber(userList.getPhonenumber());
//            sysUserVO.setCreateTime(userList.getCreateTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime());
//            sysUserVO.setRemark(userList.getRemark());
//            sysUserVO.setSex(userList.getSex());
//            sysUserVOS.add(sysUserVO);
//
//
//
//        }
//
//
//        return AjaxResult.success(sysUserVOS);
//    }


    /*
     */
    /**
     * 查询列表
     *
     * @return
     *//*

    @GetMapping("listUser")
    public AjaxResult listUser() {
        // 获取所有用户
        List<SysUser> userLists = userService.list();
        ArrayList<SysUserVO> sysUserVOS = new ArrayList<>();

        // 遍历用户列表
        for (SysUser userList : userLists) {
            SysUserVO sysUserVO = new SysUserVO();
            sysUserVO.setUserName(userList.getUserName());
            sysUserVO.setPhonenumber(userList.getPhonenumber());
            sysUserVO.setCreateTime(userList.getCreateTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime());
            //sysUserVO.setRemark(userList.getRemark());
            sysUserVO.setSex(userList.getSex());

            // 查询多表
            List<SysUserRole> userRoles = sysRoleService.getUserRolesByUserId(userList.getUserId());
            List<String> roleNames = new ArrayList<>();
            // 获取角色名称
            for (SysUserRole userRole : userRoles) {
                SysRole sysRole = sysRoleService.getRoleById(userRole.getRoleId());
                if (sysRole != null) {
                    roleNames.add(sysRole.getRoleName());  // 将角色名称加入列表
                }
            }

            sysUserVO.setRoleNames(roleNames);  // 设置角色信息

            sysUserVOS.add(sysUserVO);
        }

        return AjaxResult.success(sysUserVOS);
    }
*/


    @Autowired
    private ISysUserAttributeService sysUserAttributeService;


    @GetMapping("listUser")
    public AjaxResult listUser() {
        // 获取所有用户
        List<SysUser> userLists = userService.list();
        // 获取所有用户属性，转换为Map方便查找
        List<SysUserAttribute> attributes = sysUserAttributeService.list();
        HashMap<Integer, String> attributeMap = new HashMap<>(attributes.size());
        for (SysUserAttribute attribute : attributes) {
            attributeMap.put(attribute.getId(), attribute.getName());
        }
        System.out.println("我是Map: " + attributeMap);

        // 获取系统默认时区
        ZoneId zoneId = ZoneId.systemDefault();

        // 创建返回的VO列表
        List<SysUserVO> result = new ArrayList<>();
        for (SysUser user : userLists) {
            SysUserVO sysUserVO = new SysUserVO();
            sysUserVO.setUserName(user.getUserName());
            sysUserVO.setPhonenumber(user.getPhonenumber());
            sysUserVO.setSex(user.getSex());
            sysUserVO.setCreateTime(user.getCreateTime().toInstant().atZone(zoneId).toLocalDateTime());

            // 设置属性名称，若为null则显示默认值
            Integer attributeId = user.getAttributeId();
            if (attributeId != null) {
                //sysUserVO.setProperty(attributeMap.getOrDefault(attributeId, "未定义"));
                sysUserVO.setAttributeName(attributeMap.getOrDefault(attributeId, "未定义"));

            } else {
               // sysUserVO.setProperty("未定义");
                sysUserVO.setAttributeName("未定义");
            }

            result.add(sysUserVO);
        }

        // 返回结果
        return AjaxResult.success(result);
    }


    /**
     * 新增用户
     */
  //  @PostMapping("add/user")
//    public AjaxResult addUser(@RequestBody UserDTO userDTO) {
//        SysUser sysUser = new SysUser();
//        userService.insert(sysUser);
//
//
//        return AjaxResult.success();
//    }



    @PostMapping("add/user")
    @Transactional
    public AjaxResult register(@RequestBody SysUser user) {
        // 手机号码格式验证
        String phonenumber = user.getPhonenumber();
        if (!phonenumber.matches(PHONE_NUMBER)) {
            log.error("手机号：{} 格式不正确", phonenumber);
            return AjaxResult.error(400, "手机号码格式不正确");
        }

        // 用户数据验证
        if (ObjectUtils.isNotEmpty(phonenumber)) {
            // 检查手机号是否唯一
            long count = userService.count(new LambdaQueryWrapper<SysUser>()
                    .eq(SysUser::getPhonenumber, phonenumber));
            if (count > 1) {
                log.error("在数据库中找到了多条手机号：{}", phonenumber);
                return AjaxResult.error(409, "手机号码不唯一，找到了多条记录");
            }

            // 检查手机号是否已经存在
            SysUser existingUser = userService.getOne(new LambdaQueryWrapper<SysUser>()
                    .eq(SysUser::getPhonenumber, phonenumber),false);
            if (ObjectUtils.isNotEmpty(existingUser)) {
                log.info("用户：{} 手机号码：{} 已存在", existingUser.getUserName(), phonenumber);
                return AjaxResult.error(409, "用户'" + phonenumber + "'注册失败，手机号码已存在");
            }
        }

        // 设置用户默认字段
        user.setNickName(phonenumber);
        user.setUserName(phonenumber);
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        // 尝试插入用户数据
        try {
            boolean isInserted = userService.insertUser(user);
            if (isInserted) {
                log.info("用户：{} 注册成功", phonenumber);
                return AjaxResult.success("注册成功");
            } else {
                log.warn("用户：{} 注册失败，未知原因", phonenumber);
                return AjaxResult.error(503, "注册失败，服务暂时不可用");
            }
        } catch (DataIntegrityViolationException e) {
            log.error("事务回滚：手机号 {} 已存在，违反唯一性约束", phonenumber);
            return AjaxResult.error(422, "注册失败，手机号已存在");
        } catch (Exception e) {
            log.error("事务回滚：{}", e.getMessage());
            return AjaxResult.error(500, "注册失败，系统异常");
        }

    }
}
